<?php
namespace app\admin\controller;
use think\Controller;

Class Link extends BaseAdmin
{

	//品牌列表
    public function lst()
    {
    	
        
        $linkRes=db('tp_link')->paginate(3);
        $this->assign('linkRes',$linkRes);
        // dump($data->render());
        // exit;
        return $this->fetch('list');
    }

    //品牌添加
    public function add()
    {
    	 
        if(request()->isPost()){
        	$data=input('post.');
        	if($data['link_url']&&stripos($data['link_url'],'http://')===false){
        		$data['link_url']='http://'.$data['link_url'];
        	}

        	if($_FILES['logo']['tmp_name']){
        		$data['logo']=$this->upload();
        	}


        	//验证
        	// $validate = new \app\admin\validate\link;
        	// if (!$validate->check($data)) {
        	// 	$this->error($validate->getError());
        	// }
        	
        	$add=db('tp_link')->insert($data);
        	if($add){
        		$this->success('保存成功','lst');
        	}
        	else{
        		$this->error('保存失败');
        	}

        }
        return $this->fetch();

    }

    //品牌编辑
    public function edit($id)
    {
    	$linkRes=db('tp_link')->where(array('id'=>$id))->find();
    	$this->assign('linkRes',$linkRes);
    	if(request()->isPost()){
        	$data=input('post.');
        	if($data['link_url']&&stripos($data['link_url'],'http://')===false){
        		$data['link_url']='http://'.$data['link_url'];
        	}

        	if($_FILES['logo']['tmp_name']){
        		$data['logo']=$this->upload();
        	}
        	$up=db('tp_link')->where(array('id'=>$id))->update($data);
        	// dump($up);
        	// exit;
        	if($up!==false){
        		$this->success('保存成功','lst');
        	}
        	else{
        		$this->error('保存失败');
        	}

        }
        return $this->fetch();
    }



    //品牌删除
    public function del($id)
    {
        $tp=db('tp_link');
        $del=$tp->delete($id);
    	$img=$tp->field('logo')->find($id);
        if($img['logo']){
            $img=IMG_UPLOADS.$img['logo'];
            
            if(file_exists($img)){
            unlink($img);
        }

        }
        
    	if($del){
    		$this->success('删除成功','lst');

    	}else{
            $this->error('删除失败');
    	}
    	
        return $this->fetch();
    }

    
    //图片上传
	public function upload(){
		$file=request()->file('logo');
		if($file==null){
			exit(json_encode(array('msg'=>'没有文件上传')));
		}
		$info=$file->move('../public/static/uploads');
		$ext=$info->getExtension();//获取后缀名
		if(!in_array($ext,array('jpg','png','gif','jpeg'))){
			exit(json_encode(array('msg'=>'文件格式不符合')));
		}
		if($info){
			return $img=$info->getSaveName();

		}else{
			$file->getError();
			die;
		}
		
		
	}


}